package com.aeye.mbr.upms.client.interceptor;

import com.aeye.mbr.common.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Description: </p>
 *
 * @author zhouchuanbo
 * @version 1.0
 * @date 2018/3/27 0027
 */
public class CSRFInterceptor extends HandlerInterceptorAdapter {
    private static final Logger log = LoggerFactory
            .getLogger(CSRFInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        if ("POST".equalsIgnoreCase(request.getMethod())) {
            //白名单
            if(request.getRequestURI().startsWith("/common/")){
                return true;
            }

            String contextPath = request.getContextPath();

            String uri = request.getRequestURI();
            if (contextPath.length() > 0) {
                uri = uri.substring(contextPath.length());
            }
            if ("/sso/error.html".equals(uri))
            {
                return true;
            }

             String csrfToken = CSRFTokenManager.getTokenFromRequest(request);

            String aaaaa = request.getHeader("x-requested-with");
            String bbbb = request.getMethod();

            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            String ddd = ((HttpServletRequest) request).getSession().getId().toString();
            String ff = session.getId().toString();
            String aaa = CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME + "_" + session.getId();
            String token =  RedisUtil.get(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME + "_" + session.getId());

            if (StringUtils.isEmpty(csrfToken) || !csrfToken.equals(token))
            {
                log.error("跨站请求伪造,请求非法，csrfToken为" + csrfToken+ " ，服务器token为" + token +" 。");

                String path = ((HttpServletRequest) request).getContextPath();
                String basePath = request.getScheme() + "://" + request.getServerName()
                        + ":" + request.getServerPort() + path + "/";
            	if (request.getHeader("x-requested-with")!= null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
            		
           		    response.setHeader("SECURITYSTATUS", "NOT");  
                    response.setHeader("CONTEXTPATH", basePath+"sso/error.html");  
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);  
                    return false;  
            	}

               request.getRequestDispatcher("/sso/error.html").forward(request, response);
               log.error("=====星号星号=====:" + request.getRequestURI());
            }
        }

        return true;
    }

    private String getCurrentUrl(HttpServletRequest request) {

        String currentUrl = request.getRequestURL().toString();

        if (!StringUtils.isEmpty(request.getQueryString())) {

            currentUrl += "?" + request.getQueryString();

        }
        return currentUrl;
    }
}